import axios from "axios";
import store from '@/store'
import { Toast } from "antd-mobile";
import { getTokenInfo, setTokenInfo , removeTokenInfo} from "./storage";
import { history } from './history'

const http = axios.create({
    baseURL: 'http://toutiao.itheima.net/v1_0/'
})

http.interceptors.request.use((config) => {
  // const token = getTokenInfo()
  // console.log(token);
  const {
    login: { token },
  } = store.getState()
  if (token) {
    // 设置请求头的 Authorization 字段
    config.headers['Authorization'] = `Bearer ${token}`
  }
    return config
  })
  
http.interceptors.response.use(
    (response) => {
      return response.data
    },
    async (error) => {
      if (!error.response) {
        Toast.show('网络繁忙，请稍后再试')
        return Promise.reject(error)
      }
      if(error.response.status!==401){
        Toast.show(error.response.data.message)
        return Promise.reject(error)
      }
      let { token , refresh_token } = getTokenInfo()
      // 没有token，回去login重新获取
      if (!token || !refresh_token) {
        history.replace('/login')
        return Promise.reject(error)
      }
      try {
        const res = await http.put('/authorizations', null, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            Authorization: `Bearer ${refresh_token}`,
          },
        })
        setTokenInfo({
          refresh_token,
          token: res.data.data.token
        }) 
      } catch (err) {
        removeTokenInfo()
        history.push('/login')
        return Promise.reject(error)
      }

      return Promise.reject(error)
    }
  )
  
  export default http